import ajax from '../main.js';
import '../../css/systemManage/systemManage.scss';
import '../../js/token'

const searchData = {
    type: 'name',
    value: '',

}

// 读取本地资料 给顶部 头像赋值----
let userInfo = JSON.parse(localStorage.userInfo);
let [{ avatar, uname }] = userInfo;

$('#nav_avatar').html(`
    <img src="${avatar}" class="layui-nav-img">${uname}
`)


layui.use('table', function () {
    var table = layui.table;

    var userTable = table.render({
        elem: '#userTable',
        cols: [[
            { type: 'checkbox', fixed: 'left' },
            { field: 'name', width: 120, title: '姓名', fixed: 'left' },
            { field: 'uname', width: 120, title: '昵称' },
            { field: 'phone', width: 180, title: '手机号' },
            { field: 'section', title: '所属机构' },
            { field: 'createTime', title: '创建时间' },
            {
                field: 'state', width: 120, title: '状态', align: 'center', templet: function (d) {
                    if (d.state == '启用') {
                        return `
                            <span class="layui-btn layui-btn-primary layui-border-green layui-btn-xs">${d.state}</span>`
                    } else {
                        return `
                            <span class="layui-btn layui-btn-primary layui-border-red layui-btn-xs">${d.state}</span>`
                    }

                }
            },
            {
                fixed: 'right', align: 'center', title: '操作', templet: function (d) {
                    // console.log(d);
                    if (d.state == '启用') {
                        return `
                        <a class="layui-btn layui-btn-primary layui-border-red layui-btn-xs" lay-event="change" data-id='${d._id}'>禁用</a>
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                        `
                    } else {
                        return `
                        <a class="layui-btn layui-btn-primary layui-border-green layui-btn-xs" lay-event="change" class="open" data-id='${d._id}'>启用</a>
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                        `
                    }

                }
            }
        ]],
        page: true,
        limit: 5,
        limits: [5, 10, 20, 30, 40],
        height: 'full-250',
        url: 'http://localhost:3000/system/searchUsers',
        where: searchData,
        parseData: function (res) { //res 即为原始返回的数据
            // console.log(res);
            return {
                "code": res.code, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.total, //解析数据长度
                "data": res.findUsers //解析数据列表
            };
        }
    });


    //监听表格复选框选择
    table.on('checkbox(userTable)', function (obj) {
        // console.log(obj)
    });
    //监听工具条操作-----------------
    table.on('tool(userTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'change') {
            let state = $(this).text();
            let _id = $(this).data('id');
            ajax({
                url: '/system/changeState',
                data: {
                    _id,
                    state
                }
            })
            // 连续点击会出错
            table.reload('userTable', {
                where: searchData
                , page: {
                    curr: $(".layui-laypage-em").next().html() //停留在哪一页
                }
            });
        } else if (obj.event === 'del') {
            layer.confirm('确认删除该条数据么?', async function (index) {
                console.log(obj);
                const res = await ajax({
                    url: '/system/delUser',
                    type: 'POST',
                    data: {
                        _id: data._id
                    }
                })
                if (res.code == 200) {
                    alert('删除成功');
                    table.reload('userTable', {
                        where: searchData
                        , page: {
                            curr: $(".layui-laypage-em").next().html() //停留在哪一页
                        }
                    });
                }
                // obj.del();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            console.log(data);
            layui.use('form', function () {
                var form = layui.form, $ = layui.$;
                layer.open({
                    title: '编辑',
                    type: 1,
                    area: '600px',
                    btn: ['确认修改'],
                    content: $('#add_organ'),
                    success: async function () {
                        form.render('select');
                        let sections = await ajax({
                            url: '/system/' + $('#sel_organ').val(),
                        });
                        // console.log(sections);
                        let secHtml = sections.map(item => `
                            <option value="${item._id}" >${item.name}</option>
                        `).join('');
                        $('#sel_section').html(secHtml);
                        form.render('select');
                        // 表单赋值--------------
                        // 截取 section的值 放入下拉框
                        let section = data.section.split('- ');
                        form.val("add_organ", {
                            "user_name": data.name
                            , "user_uname": data.uname
                            , "user_phone": data.phone
                        });
                        console.log(section);
                        $('#sel_organ').next().find('input').val(section[0]);
                        $('#sel_section').next().find('input').val(section[1]);

                    },
                    yes: async function (index, layero) {
                        // 获取编辑的信息,发送后台
                        const organ_name = $('#sel_organ').next().find('input').val();
                        const section_name = $('#sel_section').next().find('input').val();
                        const section = organ_name + ' - ' + section_name;
                        console.log(section);
                        const { user_name, user_uname, user_phone } = form.val("add_organ");
                        console.log(user_name, user_uname, user_phone);
                        const userData = {
                            _id: data._id,
                            section,
                            user_name,
                            user_uname,
                            user_phone,
                        }
                        // 这里加上 await 的话会影响关闭弹出层!!!
                        ajax({
                            url: '/system/updateUser',
                            type: 'POST',
                            data: userData
                        });
                        alert('修改成功');
                        table.reload('userTable', {
                            where: searchData
                            , page: {
                                curr: $(".layui-laypage-em").next().html() //停留在哪一页
                            }
                        });
                        //重置表单
                        $('#add_organ')[0].reset();
                        form.render();
                        layer.closeAll(); //如果设定了yes回调，需进行手工关闭
                    }
                })

                form.on('select(sel_organ)', async function (data) {
                    console.log(data.value); //得到被选中的值
                    let sections = await ajax({
                        url: '/system/' + data.value,
                    });
                    // console.log(sections);
                    let secHtml = sections.map(item => `
                    <option value="${item._id}" >${item.name}</option>
                `).join('');
                    $('#sel_section').html(secHtml);
                    form.render('select');

                });

            })
        }
    });

    // 获取机构 渲染到新增的下拉框里----------------
    async function getOrgan() {
        const organ = await ajax({
            url: "/system/getOrgan"
        })
        let options = organ.map(item =>
            `<option value="${item._id}">${item.name}</option>`
        ).join('');
        $('#sel_organ').html(options)
    }
    getOrgan();

    // 绑定新增按钮
    $('#addOrgan').click(function () {
        layui.use('form', function () {
            var form = layui.form, $ = layui.$;
            layer.open({
                title: '新增用户',
                type: 1,
                area: '600px',
                btn: ['确认新增'],
                content: $('#add_organ'),
                success: async function () {
                    $('#add_organ')[0].reset();
                    form.render();
                    // form.render('select');
                    let sections = await ajax({
                        url: '/system/' + $('#sel_organ').val(),
                    });
                    // console.log(sections);
                    let secHtml = sections.map(item => `
                    <option value="${item._id}" >${item.name}</option>
                `).join('');
                    $('#sel_section').html(secHtml);
                    form.render('select');
                },
                yes: async function (index, layero) {
                    // 获取新增信息,发送后台
                    const organ_name = $('#sel_organ').next().find('input').val();
                    const section_name = $('#sel_section').next().find('input').val();
                    const section = organ_name + ' - ' + section_name;
                    console.log(section);
                    const { user_name, user_uname, user_phone } = form.val("add_organ");
                    console.log(user_name, user_uname, user_phone);
                    // 当天时间
                    const dt = new Date();
                    const createTime = dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
                    const data = {
                        section,
                        user_name,
                        user_uname,
                        user_phone,
                        createTime
                    }
                    const result = await ajax({
                        url: '/system',
                        type: 'POST',
                        data
                    })
                    if (result.code == 200) {
                        alert('新增成功');
                        table.reload('userTable', {
                            where: searchData
                            , page: {
                                curr: $(".layui-laypage-em").next().html() //停留在哪一页
                            }
                        });
                    }
                    //重置表单
                    $('#add_organ')[0].reset();
                    form.render();
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                }
            })

            form.on('select(sel_organ)', async function (data) {
                console.log(data.value); //得到被选中的值
                let sections = await ajax({
                    url: '/system/' + data.value,
                });
                // console.log(sections);
                let secHtml = sections.map(item => `
                <option value="${item._id}" >${item.name}</option>
            `).join('');
                $('#sel_section').html(secHtml);
                form.render('select');

            });

        })
    })

    // 搜索功能-----------
    $('#user-searchBtn').click(function () {
        searchData.value = $('#user-input').val();
        table.reload('userTable', {
            where: searchData
            , page: {
                curr: 1
            }
        });
    })

    // 多条删除----
    $('#delUser').click(function () {
        layer.confirm('确认删除这些数据么?', async function (index) {
            var checkStatus = table.checkStatus('userTable'), data = checkStatus.data;
            let usersId = data.map(item => {
                return {
                    id: item._id
                }
            })
            // console.log(JSON.stringify(usersId));
            ajax({
                url: '/system/delUsers',
                type: 'POST',
                data: {
                    usersId: JSON.stringify(usersId)
                }
            });
            alert('删除成功')
            table.reload('userTable', {
                where: searchData,
                page: {
                    curr: 1 //停留在哪一页
                }
            });
            layer.close(index);
        });

    })

    $('#exportUser').click(function () {
        table.exportFile(userTable.config.id, data); //data 为该实例中的任意数量的数据
    })
});



